package youcaihuaoa.weetop.com.ui.web

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.ViewGroup
import android.webkit.*
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.*
import com.gyf.immersionbar.ktx.immersionBar
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.util.ImagePathUtil
import com.robot.base.util.WebViewUtil
import com.robot.base.utils.ChoiceImgHelper
import youcaihuaoa.weetop.com.BR
import youcaihuaoa.weetop.com.R
import youcaihuaoa.weetop.com.databinding.AppActivityWebBinding
import youcaihuaoa.weetop.com.vm.web.WebViewModel
import java.io.File
import java.io.IOException

/**
 *  网页详情
 */
@Route(path = AppConstants.Router.Main.A_WEB)
class WebActivity : GLBaseActivity<AppActivityWebBinding, WebViewModel>() {

    private var mFilePathCallback: ValueCallback<Array<Uri>>? = null
    private var mCameraPhotoPath: String? = null
    var PERMISSION_REQUEST_CODE = 0
    val INPUT_FILE_REQUEST_CODE = 1
    private var mUploadMessage: ValueCallback<Uri>? = null
    private val FILECHOOSER_RESULTCODE = 2
//    private var dkWebView: DKWebView? = null


    override fun initContentView(savedInstanceState: Bundle?): Int = R.layout.app_activity_web

    override fun initVariableId(): Int = BR.viewModel

    var webUrl = ""
    var refresh = false
    var type = ""

    override fun initComponents() {
        webUrl = intent.getStringExtra(AppConstants.BundleKey.WEB_URL) ?: ""
//沉浸式状态栏
        val showBack = intent.getBooleanExtra(AppConstants.BundleKey.WEB_SHOW_BACK, false)
        if (showBack) {
            addSingleTitleBar("")
        }
//        dkWebView = DKWebView(this)
//        addContentView(
//            dkWebView,
//            ViewGroup.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.MATCH_PARENT
//            )
//        )
        WebViewUtil.initWebViewSettings(binding.dkWebView, this)
        binding.dkWebView?.addJavascriptInterface(this, "Android")
        binding.dkWebView?.webChromeClient = mWebChromeClient

        immersionBar {
            if (!showBack) {
                transparentStatusBar()
            }
            keyboardEnable(true)
            fitsSystemWindows(showBack)
        }
        LogUtils.e(webUrl)
        binding.dkWebView.loadUrl(
            webUrl
        )//
    }

    override fun notNetWork() {
        super.notNetWork()
    }

    override fun hasNetWork() {
        super.hasNetWork()
    }


    override fun onDestroy() {
        super.onDestroy()
        (binding.dkWebView?.parent as ViewGroup).removeView(binding.dkWebView)
        binding.dkWebView?.clearHistory()
        binding.dkWebView?.clearView()
        binding.dkWebView?.removeAllViews()
        binding.dkWebView?.destroy()
//        binding.dkWebView = null
    }


    private val mWebChromeClient = object : WebChromeClient() {

        // android 5.0 这里需要使用android5.0 sdk
        override fun onShowFileChooser(
            webView: WebView, filePathCallback: ValueCallback<Array<Uri>>,
            fileChooserParams: FileChooserParams
        ): Boolean {
            mFilePathCallback?.onReceiveValue(null)

            mFilePathCallback = filePathCallback

            /**
             * Open Declaration   String android.provider.MediaStore.ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"
             * Standard Intent action that can be sent to have the camera application capture an image and return it.
             * The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT. As of android.os.Build.VERSION_CODES.LOLLIPOP, this uri can also be supplied through android.content.Intent.setClipData(ClipData). If using this approach, you still must supply the uri through the EXTRA_OUTPUT field for compatibility with old applications. If you don't set a ClipData, it will be copied there for you when calling Context.startActivity(Intent).
             * See Also:EXTRA_OUTPUT
             * 标准意图，被发送到相机应用程序捕获一个图像，并返回它。通过一个额外的extra_output控制这个图像将被写入。如果extra_output是不存在的，
             * 那么一个小尺寸的图像作为位图对象返回。如果extra_output是存在的，那么全尺寸的图像将被写入extra_output URI值。
             */
            ChoiceImgHelper.ChoiceImg(
                ActivityUtils.getTopActivity(), 6, false, {
                    var results: Array<Uri>? = null
                    val uris = arrayListOf<Uri>()
                    it.forEach { it1 ->
//                        uploadFile(File(it1.compressPath))
                        uris.add(Uri.fromFile(File(it1?.compressPath ?: "")))
                    }
                    results = uris.toTypedArray()
                    mFilePathCallback!!.onReceiveValue(results)
                    mFilePathCallback = null
                },
                {
                    onActivityResult(1, 0, null)
                }
            )
            return true
        }
    }

    //在sdcard卡创建缩略图
    //createImageFileInSdcard
    @SuppressLint("SdCardPath")
    private fun createImageFile(): File {
        //mCameraPhotoPath="/mnt/sdcard/tmp.png";
        val file = File(
            Environment.getExternalStorageDirectory(), "/temp/" +
                    System.currentTimeMillis() + ".jpg"
        )
        mCameraPhotoPath = file.absolutePath
        if (!file.parentFile!!.exists()) {
            try {
                file.parentFile!!.mkdirs()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return file
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return
            var result = if (data == null || resultCode != Activity.RESULT_OK)
                null
            else
                data.data
            if (result != null) {
                val imagePath = ImagePathUtil.getImageAbsolutePath(this, result)
                if (!TextUtils.isEmpty(imagePath)) {
                    result = Uri.parse("file:///$imagePath")
                }
            }
            mUploadMessage!!.onReceiveValue(result)
            mUploadMessage = null
        } else if (requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null) {
            // 5.0的回调
            var results: Array<Uri>? = null

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data1, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = arrayOf<Uri>(Uri.parse(mCameraPhotoPath))
                    }
                } else {
                    val uri = data.data;
                    if (uri != null) {
                        //没设置Intent.EXTRA_ALLOW_MULTIPLE，会回调这个
//                        onActivityCallBack(uri);
                        results = arrayOf<Uri>(uri)
                    } else if (data.clipData != null) {
                        //设置Intent.EXTRA_ALLOW_MULTIPLE，会回调这个
                        val clipData = data.clipData;
                        val count = clipData?.itemCount ?: 0
                        if (count > 0) {
                            val uris = arrayListOf<Uri>()
                            for (i in 0 until count) {
                                uris.add(clipData?.getItemAt(i)?.uri!!)
                            }
                            results = uris.toTypedArray()
                        } else {
                        }
                    }
//                    val dataString = data.dataString

//                    if (dataString != null) {
//                        results = arrayOf<Uri>(Uri.parse(dataString))
//                    }
                }
            }

            mFilePathCallback!!.onReceiveValue(results)
            mFilePathCallback = null
        } else {
            super.onActivityResult(requestCode, resultCode, data)
            return
        }
    }
}